/**
 * Copyright 2015 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2015年10月5日 上午10:51:46
 */
package com.absir.appserv.system.asset;

import java.io.IOException;

import com.absir.appserv.system.bean.JPayTrade;
import com.absir.appserv.system.bean.value.JePayStatus;
import com.absir.appserv.system.helper.HelperJson;
import com.absir.appserv.system.service.AnzhiService;
import com.absir.appserv.system.service.BeanService;
import com.absir.appserv.system.service.utils.PayUtils;
import com.absir.server.in.Input;
import com.absir.server.value.Body;
import com.absir.server.value.Param;
import com.absir.server.value.Server;
import com.anzhi.util.Des3Util;
import com.fasterxml.jackson.core.JsonProcessingException;

/**
 * @author absir
 *
 */
@Server
public class Asset_anzhi extends AssetServer {

	/**
	 * @author absir
	 *
	 */
	public static class NotifyData {

		public String uid;

		public String orderId;

		public String orderAmount;

		public String code;

		public float payAmount;

		public String cpInfo;

	}

	/**
	 * @param data
	 * @param input
	 * @return
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@Body
	public String notify(@Param String data, Input input) throws JsonProcessingException, IOException {
		data = Des3Util.decrypt(data, AnzhiService.ANZHI_CONFIGURE.getMerchantKey());
		NotifyData notifyData = HelperJson.decode(data, NotifyData.class);
		JPayTrade payTrade = BeanService.ME.get(JPayTrade.class, notifyData.cpInfo);
		if (payTrade != null) {
			payTrade.setPlatform(AnzhiService.PLAT_FORM_NAME);
			String pay_status = notifyData.code;
			payTrade.setStatus(pay_status.equals("1") && notifyData.payAmount >= payTrade.getAmount() ? JePayStatus.PAYED
					: JePayStatus.ERROR);
			payTrade.setStatusData(pay_status);
			if (payTrade.getStatus() == JePayStatus.PAYED) {
				PayUtils.proccessDone(payTrade);

			} else {
				BeanService.ME.merge(payTrade);
			}
		}

		return "success";
	}

}
